<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="200px">
      <el-form-item label="财务分类" prop="parentName">
        <el-popover
          ref="dataListPopover"
          placement="bottom-start"
          trigger="click">
          <el-tree
            :data="dataList"
            :props="dataListTreeProps"
            node-key="id"
            ref="dataListTree"
            @current-change="dataListTreeCurrentChangeHandle"
            :default-expand-all="true"
            :highlight-current="true"
            :expand-on-click-node="false">
          </el-tree>
        </el-popover>
        <el-input v-model="dataForm.parentName" v-popover:dataListPopover  :readonly="true" placeholder="点击选择分类" class="menu-list__input"></el-input>
      </el-form-item>
      <el-form-item label="缴费日期" prop="payDate">
        <el-date-picker v-model="dataForm.payDate" type="date"  placeholder="缴费日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" ></el-date-picker>
      </el-form-item>
      <el-form-item label="配合人" >
        <div v-for="(ele,index) in partnerList" :key="index">
          <el-select v-model="partnerId[ele.partner]" filterable :placeholder="ele.partnerName" @change = '((val) => {getPartnerId(val,ele.partner)})'>
            <el-option
              v-for="item in teacherList"
              :key="item.id"
              :label="item.teacherName"
              :value="item.id">
            </el-option>
          </el-select><br/>
        </div>
      </el-form-item>
      <el-form-item label="项目" prop="cardTypeId" >
        <el-select v-model="dataForm.cardTypeId" placeholder= "会员卡类型"  @change = '((val) => {getAmount(val)})' >
          <el-option v-for="(item, index) in payeeoption"
                     :label="item.cardName"
                     :key="item.cardName"
                     :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="会员折扣卡" prop="cardTypeId" >
        <el-select v-model="dataForm.baseVipId" placeholder= "会员卡类型"  @change = 'getVipDiscount' >
          <el-option v-for="(item, index) in baseVip"
                     :label="item.vipName"
                     :key="item.id"
                     :value="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="装备" prop="equipment">
        <el-input v-model="dataForm.equipment" placeholder="装备"></el-input>
      </el-form-item>
      <el-form-item label="订单金额" prop="orderAmount">
        <el-input v-model="dataForm.orderAmount" placeholder="订单金额"></el-input>
        价格:{{this.amount}} - 折扣金额:{{this.amount * (100 - discount.discount) / 100}}
      </el-form-item>
      <el-form-item label="学员姓名" prop="studentName">
        <el-input v-model="dataForm.studentName" placeholder="学员姓名"></el-input>
      </el-form-item>
      <el-form-item label="学员性别" prop="studentSex">
        <el-select v-model="dataForm.studentSex" placeholder= "会员卡类型"  >
          <el-option v-for="(item, index) in sexOptions"
                     :label="item.label"
                     :key="item.value"
                     :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学员生日" prop="studentAge">
        <el-date-picker v-model="dataForm.studentAge" type="date"  placeholder="学员生日" format="yyyy-MM-dd" value-format="yyyy-MM-dd" ></el-date-picker>
      </el-form-item>
      <el-form-item label="新老会员" prop="isOld">
        <el-select v-model="dataForm.isOld" placeholder= "新老会员"  >
          <el-option v-for="(item, index) in isOldOptions"
                     :label="item.label"
                     :key="item.value"
                     :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="dataForm.phone" placeholder="电话"></el-input>
      </el-form-item>
      <el-form-item label="家庭住址" prop="address">
        <el-input v-model="dataForm.address" placeholder="家庭住址"></el-input>
      </el-form-item>
      <el-form-item label="现就读学校" prop="school">
        <el-input v-model="dataForm.school" placeholder="现就读学校"></el-input>
      </el-form-item>
      <el-form-item label="来源" prop="source">
        <!-- <el-input v-model="dataForm.source" placeholder="来源"></el-input> -->
        <el-select v-model="dataForm.source" placeholder="来源">
          <el-option v-for="item in sourceList"
                      :label="item.channel"
                      :key="item.id"
                      :value="item.channel"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="缴费方式" prop="payType">
        <!-- <el-input v-model="dataForm.payType" placeholder="缴费方式"></el-input> -->
        <el-select v-model="dataForm.payType" placeholder="缴费方式">
          <el-option v-for="item in payTypeList"
                      :label="item.payType"
                      :key="item.id"
                      :value="item.payType"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="dataForm.remarks" placeholder="备注"></el-input>
      </el-form-item>
      <el-form-item label="支付凭证" prop="image">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :action="url"
          :before-upload="beforeUploadHandle"
          :on-success="successHandle">
          <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width:200px;height:auto;">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<script>
  import { treeDataTranslate } from '@/utils'
  export default {
    data () {
      return {
        visible: false,
        dataForm: {
          id: 0,
          category: '',
          pid: '',
          fatherCategory: [],
          parentId: 0,
          parentName: '',
          studentId: null,
          studentName: '',
          orderAmount: 0,
          cardTypeId: '',
          studentSex: '',
          studentAge: '',
          isOld: '',
          phone: '',
          address: '',
          school: '',
          source: '',
          payType: '',
          pic: '',
          payDate: '',
          equipment: '',
          yaoyue: '',
          tiyan: '',
          genjin: '',
          remarks: '',
          yaoyueId: '',
          tiyanId: '',
          genjinId: '',
          baseVipId: ''
        },
        url: this.$http.adornUrl(`/business/teacher/uploadPicture?type=payment&token=${this.$cookie.get('token')}`),
        imageUrl: '',
        dataRule: {
          studentName: [{
            required: true,
            message: '学员姓名不能为空',
            trigger: 'blur'
          }],
          orderStatus: [{
            required: true,
            message: '订单状态不能为空',
            trigger: 'blur'
          }],
          payDate: [{
            required: true,
            message: '缴费日期不能为空',
            trigger: 'blur'
          }],
          cardTypeId: [{
            required: true,
            message: '项目不能为空',
            trigger: 'blur'
          }],
          phone: [{
            required: true,
            message: '联系方式不能为空',
            trigger: 'blur'
          }],
          orderAmount: [{
            required: true,
            message: '订单金额不能为空',
            trigger: 'blur'
          }],
          source: [{
            required: true,
            message: '来源不能为空',
            trigger: 'blur'
          }],
          payType: [{
            required: true,
            message: '缴费方式不能为空',
            trigger: 'blur'
          }]
        },
        dataList: [],
        studentList: [],
        dataListTreeProps: {
          label: 'category',
          children: 'children'
        },
        sexOptions: [
          {
            value: 0,
            label: '女'
          },
          {
            value: 1,
            label: '男'
          }
        ],
        isOldOptions: [
          {
            value: 0,
            label: '新'
          },
          {
            value: 1,
            label: '老'
          }
        ],
        sourceList: [],
        payTypeList: [],
        teacherList: [],
        partnerList: [],
        partnerId: [],
        amount: 0,
        baseVip: [],
        discount: {
          discount: 0
        },
        payeeoption: []
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/business/cwOrder/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.dataForm.parentId = data.cwOrder.categoryId
                this.dataForm.parentName = data.cwOrder.categoryName
                this.dataForm.studentId = data.cwOrder.studentId
                this.dataForm.studentName = data.cwOrder.studentName
                this.dataForm.studentAge = data.cwOrder.studentAge
                this.dataForm.payDate = data.cwOrder.payDate
                this.dataForm.orderAmount = data.cwOrder.orderAmount
                this.dataForm.serviceCharge = data.cwOrder.serviceCharge
                this.dataForm.preferentialAmount = data.cwOrder.preferentialAmount
                this.dataForm.amountPayable = data.cwOrder.amountPayable
                this.dataForm.amountPaid = data.cwOrder.amountPaid
                this.dataForm.paymentTime = data.cwOrder.paymentTime
                this.dataForm.subscriptionTime = data.cwOrder.subscriptionTime
                this.dataForm.pic = data.cwOrder.pic
                this.imageUrl = data.cwOrder.pic
                this.dataForm.cardTypeId = data.cwOrder.cardTypeId
                this.dataForm.studentSex = data.cwOrder.studentSex
                this.dataForm.studentAge = data.cwOrder.studentAge
                this.dataForm.isOld = data.cwOrder.isOld
                this.dataForm.phone = data.cwOrder.phone
                this.dataForm.address = data.cwOrder.address
                this.dataForm.school = data.cwOrder.school
                this.dataForm.source = data.cwOrder.source
                this.dataForm.payType = data.cwOrder.payType
                this.dataForm.equipment = data.cwOrder.equipment
                this.dataForm.payDate = data.cwOrder.payDate
                this.dataForm.yaoyue = data.cwOrder.yaoyue
                this.dataForm.tiyan = data.cwOrder.tiyan
                this.dataForm.genjin = data.cwOrder.genjin
                this.dataForm.remarks = data.cwOrder.remarks
                this.dataForm.baseVipId = data.cwOrder.baseVipId
                this.menuListTreeSetCurrentNode()
                // 渲染配合人
                var list = this.partnerList
                for (var i = 0; i < list.length; i++) {
                  if (list[i].partner === 1) {
                    this.partnerId[1] = data.cwOrder.yaoyueId
                  } else if (list[i].partner === 2) {
                    this.partnerId[2] = data.cwOrder.tiyanId
                  } else if (list[i].partner === 3) {
                    this.partnerId[3] = data.cwOrder.genjinId
                  }
                }
              }
            })
          } else {
            // 新增
            this.menuListTreeSetCurrentNode()
          }
        })
        this.getMemberCard()
        this.getBaseVip()
        this.getSource()
        this.getPayType()
        this.getTeacherList()
      },
      // 查询会员卡状态
      getMemberCard () {
        this.$http({
          url: this.$http.adornUrl('/business/basemembercard/getMemberCard'),
          method: 'get',
          params: ''
        }).then(({data}) => {
          this.payeeoption = data
        })
      },
      // 会员折扣卡
      getBaseVip () {
        this.$http({
          url: this.$http.adornUrl('/business/baseVip/getBaseVip'),
          method: 'get',
          params: ''
        }).then(({data}) => {
          this.baseVip = data
        })
      },
      // 查询来源
      getSource () {
        this.$http({
          url: this.$http.adornUrl('/business/basechannel/queryList'),
          method: 'get',
          params: {}
        }).then(({data}) => {
          this.sourceList = data.list
        })
      },
      // 查询配合人
      getTeacherList () {
        this.$http({
          url: this.$http.adornUrl('/business/teacher/getTeacherList'),
          mothod: 'get',
          params: {}
        }).then(({data}) => {
          if (data.code === 0) {
            this.teacherList = data.list
          }
        })
      },
      // 查询缴费方式
      getPayType () {
        this.$http({
          url: this.$http.adornUrl('/business/basepaytype/queryList'),
          method: 'get',
          params: {}
        }).then(({data}) => {
          this.payTypeList = data.list
        })
      },
      // 查询一级分类
      getFatherCategory () {
        this.$http({
          url: this.$http.adornUrl('/business/cwCategory/list'),
          method: 'get',
          params: this.$http.adornParams({

          })
        }).then(({
          data
        }) => {
          this.dataList = treeDataTranslate(data, 'id', 'pid')
        })
      },
      getPartnerId (value, index) {
        if (index === 1) {
          this.dataForm.yaoyueId = value
        } else if (index === 2) {
          this.dataForm.tiyanId = value
        } else if (index === 3) {
          this.dataForm.genjinId = value
        }
      },
      // 获取会员卡金额
      getAmount (id) {
        this.$http({
          url: this.$http.adornUrl(`/business/basemembercard/info/` + id),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.amount = data.baseMemberCard.amount
            this.dataForm.orderAmount = this.amount * this.discount.discount / 100
          }
        })
      },
      // 获取会员折扣金额
      getVipDiscount (e) {
        this.discount = this.baseVip[e]
        this.dataForm.orderAmount = this.amount * this.discount.discount / 100
      },
      // 表单提交
      dataFormSubmit () {
        if (!this.dataForm.parentId) {
          alert('分类不能为空')
          return
        }
        const amount = this.dataForm.orderAmount
        if (amount * 1 < 0) {
          alert('输入的订单金额有误')
          return
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/business/cwOrder/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'categoryId': this.dataForm.parentId,
                'studentId': this.dataForm.studentId,
                'studentName': this.dataForm.studentName,
                'cardTypeId': this.dataForm.cardTypeId,
                'studentSex': this.dataForm.studentSex,
                'studentAge': this.dataForm.studentAge,
                'isOld': this.dataForm.isOld,
                'phone': this.dataForm.phone,
                'address': this.dataForm.address,
                'school': this.dataForm.school,
                'source': this.dataForm.source,
                'payType': this.dataForm.payType,
                'orderAmount': this.dataForm.orderAmount,
                'serviceCharge': this.dataForm.serviceCharge,
                'preferentialAmount': this.dataForm.preferentialAmount,
                'amountPayable': this.dataForm.amountPayable,
                'amountPaid': this.dataForm.amountPaid,
                'paymentTime': this.dataForm.paymentTime,
                'subscriptionTime': this.dataForm.subscriptionTime,
                'pic': this.dataForm.pic,
                'equipment': this.dataForm.equipment,
                'payDate': this.dataForm.payDate,
                'yaoyue': this.dataForm.yaoyue,
                'tiyan': this.dataForm.tiyan,
                'genjin': this.dataForm.genjin,
                'remarks': this.dataForm.remarks,
                'yaoyueId': this.dataForm.yaoyueId,
                'tiyanId': this.dataForm.tiyanId,
                'genjinId': this.dataForm.genjinId,
                'baseVipId': this.dataForm.baseVipId
              })
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 菜单树选中
      dataListTreeCurrentChangeHandle (data, node) {
        this.dataForm.parentId = data.id
        this.dataForm.parentName = data.category
        this.pClose()
      },
      // 菜单树设置当前选中节点
      menuListTreeSetCurrentNode () {
        this.$refs.dataListTree.setCurrentKey(this.dataForm.parentId)
        this.dataForm.parentName = (this.$refs.dataListTree.getCurrentNode() || {})['category']
      },
      pClose () {
        this.$refs[`dataListPopover`].doClose()
      },
      beforeUploadHandle (file) {
        if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
          this.$message.error('只支持jpg、png、gif格式的图片！')
          return false
        }
        if (file.size / 1024 / 1024 > 2) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
          return false
        }
        this.num++
      },
      // 上传成功
      successHandle (response) {
        this.successNum++
        if (response && response.code === 0) {
          if (response.type === 'payment') {
            this.imageUrl = response.url
            this.dataForm.pic = response.url
          }
        }
      },
      // 获取配合人信息
      queryListByShop () {
        this.$http({
          url: this.$http.adornUrl('/business/partnerType/queryListByShop'),
          mothod: 'get',
          params: {}
        }).then(({data}) => {
          this.partnerList = data.list
        })
      }
    }
  }
</script>
